import axios from 'axios'
import { Toast, MessageBox, Indicator } from 'mint-ui'

let http = null
const baseURL = window.localStorage.apiHost + '' // 'http://qmj1.crossess.com/api';
const timeout = 60000
if (window.localStorage.init) {
  if (baseURL.indexOf('http') === -1) {
    window.location.reload()
  }
  const temp = JSON.parse(window.localStorage.init)
  if (temp.token) {
    http = axios.create({
      baseURL: baseURL,
      timeout: timeout,
      headers: {
        Authorization: temp.token
      }
    })
  } else {
    http = axios.create({
      baseURL: baseURL,
      timeout: timeout
    })
  }
} else {
  if (baseURL.indexOf('http') === -1) {
    window.location.reload()
  }
  http = axios.create({
    baseURL: baseURL,
    timeout: timeout
  })
}

function noLoading (url) {
  // 不要loading动画的接口
  const arr = [
    '/greengage/message/checkNewMessage',
    '/auth/wechat_config',
    '/greengage/user/savePicture',
    '/danmu/get',
    '/greengage/layout/set'

  ]
  let count = 0
  for (const i in arr) {
    if (url.indexOf(arr[i]) > -1) {
      count++
    }
  }
  return count === 0
}

// 添加请求拦截器
http.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  // console.log(config);
  if (noLoading(config.url)) {
    // console.log(config);
    if (config.headers.loading !== false) {
      Indicator.open()
    }
  }
  return config
}, function (error) {
  console.log(error)
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
http.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  // console.log('res:', response);

  Indicator.close()

  return response.data
}, function (error) {
  console.log(error)
  console.log(error.response)
  console.log(error.response.status)
  console.log(error.response.data)
  console.log(error.request)
  Indicator.close()
  // 对响应错误做点什么
  if (error.response) {
    console.log(error.response)
    console.log(error.response.data)
    if (error.response.data) {
      const errors = error.response.data.errors
      if (errors) {
        for (const i in errors) {
          console.log(errors[i])
          Toast(errors[i][0])
        }
        return
      }
      if (error.response.status === 404) {
        Toast('404找不到')
      }
      if (error.response.status === 429) {
        // Toast('您的操作过于频繁，请稍后再试');
        MessageBox.alert('您的操作过于频繁，请稍后再试').then(action => {

        })
      }
      /* if(error.response.status===422){
        Toast(error.response.data.msg);
      } */
      return Promise.reject(error.response.data)
    } else {
      // Toast('网络错误，请稍后重试');
    }
  } else {
    // console.log('error');
    // Toast('网络错误，请稍后重试');
  }
})
export default http
